Saturday 24 February 2018

تداول الخيارات مع r


خوارزمية خيارات التداول 1.


على الرغم من العديد من الميزات المثيرة للاهتمام من الخيارات، التجار الخاص نادرا ما الاستفادة منها (بالطبع أنا & # 8217؛ م يتحدث هنا من الخيارات الجادة، وليس الخيارات الثنائية). ربما خيارات لا تحظى بشعبية بسبب سمعتها من كونها معقدة. أو بسبب عدم وجود دعم من قبل معظم أدوات البرمجيات التجارية. أو بسبب علامات الأسعار من الأدوات القليلة التي تدعمها والبيانات التاريخية التي تحتاجها للتداول حسابي. واتيفر & # 8211؛ قمنا مؤخرا بعدة عقود برمجة لأنظمة تداول الخيارات، وفوجئت أنه حتى الأنظمة البسيطة بدا أنها تنتج أرباحا متسقة نسبيا. تبدو خيارات البيع بشكل خاص أكثر ربحا من التداول & # 8216؛ التقليدية & # 8217؛ الصكوك. هذه المقالة هي الأولى من سلسلة مصغرة عن كسب المال مع تداول الخيارات الحسابية.


الخيارات 101.


يتم شرح الخيارات على العديد من المواقع وفي العديد من الكتب التجارية، لذلك هنا & # 8217؛ مجرد لمحة سريعة. والخيار هو عقد يمنح صاحبه الحق في شراء (خيار خيار البيع) أو بيع (خيار البيع) أصلا ماليا (السعر الأساسي) بسعر ثابت (سعر الإضراب) في أو قبل تاريخ محدد (تاريخ انتهاء الصلاحية) . إذا كنت تبيع قصير (كتابة) خيارا، يمكنك & # 8217؛ أخذ الجانب الآخر من التجارة. حتى تتمكن من إدخال موقف في 4 طرق مختلفة: شراء مكالمة، شراء وضع، بيع قصيرة مكالمة، بيع قصيرة وضعت. وهذا مع كل مزيج ممكن من أسعار الإضراب وتاريخ انتهاء الصلاحية.


قسط هو السعر الذي تدفعه أو جمع لشراء أو بيع خيار. وهو أقل بكثير من سعر الأسهم الأساسية. أسواق الخيارات الرئيسية عادة ما تكون سائلة، حتى تتمكن من شراء أي وقت، كتابة، أو بيع خيار مع أي سعر الإضراب معقول وتاريخ انتهاء الصلاحية. إذا كان السعر الحالي الحالي (السعر الفوري) لخيار المكالمة فوق سعر الإضراب، فإن الخيار هو في المال؛ وإلا فإنه & # 8217؛ ق من المال. العكس هو الصحيح لخيارات وضع. في-- المال هو جيد بالنسبة للمشتري وسيئة للبائع. ويمكن ممارسة الخيارات في المال ويتم بعد ذلك تبادل للالأساسية في سعر الإضراب. الفرق بين البقعة والإضراب هو أرباح المشتري وخسارة البائع. يمكن ممارسة خيارات النمط الأمريكي في أي وقت، خيارات النمط الأوروبي فقط عند انتهاء الصلاحية.


لا يمكن ممارسة الخيارات خارج المال، على الأقل ليس في الربح. لكنها لا قيمة لها، لأنها لا تزال لديها فرصة للسير في المال قبل انتهاء الصلاحية. وتعتمد قيمة الخيار على تلك الفرصة، ويمكن حسابها للخيارات الأوروبية من السعر الفوري، والإضراب، والانتهاء، ومعدل العائد الخالي من المخاطر، ومعدل توزيعات الأرباح، والتقلب الأساسي مع صيغة بلاك سكولز الشهيرة. هذه القيمة هي أساس علاوة الخيار. قد ينحرف قسط حقيقي قليلا بسبب العرض والطلب، ومحاولات لاستباق اتجاه السعر الأساسي & # 8217؛ s.


عن طريق عكس الصيغة مع عملية تقريب، ويمكن حساب التقلب من قسط الحقيقي. هذا التقلب الضمني هو كيف تتوقع السوق أن تتذبذب الكامنة في المرة القادمة. والمشتقات الجزئية لقيمة الخيار هي الإغريق (دلتا، فيغا & # 8211؛ دون & # 8217؛ ر معرفة ما هي الرسالة اليونانية أن & # 8217؛ s من المفترض أن يكون & # 8211؛ وثيتا). أنها تحدد في أي اتجاه، ومدى قوة، سوف تتغير القيمة عندما تتغير معلمة السوق.


هذا كل المعلومات الأساسية اللازمة لخيارات التداول. بالمناسبة، انها مثيرة للاهتمام لمقارنة أداء استراتيجيات من الكتب التجارية. في حين أن الفوركس أو أنظمة تداول الأسهم الموصوفة في تلك الكتب هي في الغالب بطابقين وتفقد بالفعل في باكتست بسيط، فإنه ليس كذلك مع أنظمة الخيار. وغالبا ما يفوزون في الاختبارات الخلفية. وهذا على الرغم من أنني & # 8217؛ م متأكد من أن ما يقرب من أي مؤلف قد باكتستد حقا لهم. هل مؤلفو كتاب تداول الخيارات أكثر ذكاء من مؤلفي الكتاب التجاريين الآخرين؟ ربما، ولكننا & # 8217؛ سوف نرى أن هناك تفسير بديل.


لماذا خيارات التداول على الإطلاق؟


فهي أكثر تعقيدا وأكثر صعوبة في التجارة، وتحتاج إلى صيغة نوبل الحائز على جائزة لحساب القيمة التي بخلاف ذلك سيكون ببساطة الفرق من سعر الدخول والخروج. على الرغم من كل هذا، خيارات توفر العديد من المزايا الرائعة على الأدوات المالية الأخرى:


رافعة مالية عالية. مع 100 $ يمكنك شراء سوى عدد قليل من الأسهم، ولكن خيارات عدة مئات من الأسهم. المخاطر الخاضعة للمراقبة. يمكن لموقف قصير في سهم مسح حسابك. مواقف في خيارات يمكن أن تكون ذكية مجتمعة للحد من المخاطر في أي طريقة المرجوة. وعلى عكس وقف الخسارة انها & # 8217؛ ق حد المخاطر الحقيقية. أبعاد إضافية. أرباح الأسهم تعتمد فقط على ارتفاع أو انخفاض الأسعار. ويمكن تحقيق أرباح الخيار مع ارتفاع التقلب، وتقلب الانخفاض، وتحرك الأسعار في نطاق، من نطاق، أو أي سلوك آخر يمكن تخيله. النار وننسى. تنتهي صلاحية الخيارات، لذلك لا تحتاج إلى خوارزمية لإغلاقها (إلا إذا كنت ترغب في بيعها أو ممارستها في ظروف خاصة). وأنت تدفع أي لجنة الخروج لخيار انتهت صلاحيته. ميزة البائع. بسبب قسط، يمكن للخيارات لا تزال تنتج ربحا للبائع حتى لو التحركات الأساسية في الاتجاه الخاطئ.


تتطلب أخلاقيات القراصنة أنك لا تدعي شيئا ما فحسب، بل تثبت ذلك. للحصول على دراية الخيارات، واسمحوا & # 8217؛ ق وضعت المطالبة الأخيرة، ميزة البائع، للاختبار:


هذا هو بسيط جدا نظام التداول الخيار. فإنه يكتب عشوائيا الدعوة أو وضع خيارات ويبقي المواقف مفتوحة حتى تنتهي. بسبب وضع / الدعوة العشوائية هو الاتجاه الملحد. قبل النظر في تفاصيل الرمز، فقط تشغيله في وضع [اختبار] بضع مرات (أنت & # 8217؛ سوف تحتاج زورو الإصدار 1.53 أو أعلى). ستلاحظ أن النتيجة مختلفة في أي وقت، ولكنها غالبا ما تكون إيجابية من السلبية، على الرغم من طرح العمولة من الربح. نتيجة نموذجية:


يمكنك أن ترى أن معظم الصفقات الفوز، ولكن عندما يخسرون، فإنها تفقد كبيرة. الآن عكس الاستراتيجية وشراء الخيارات بدلا من بيعها: استبدال إنتيرشورت () من إنتيرلونغ (). تشغيله مرة أخرى بضع مرات (السيناريو يحتاج حوالي 3 ثوان ل باكتست). سترى الآن أن النتيجة غالبا ما تكون سلبية & # 8211؛ في الواقع تقريبا أي وقت.


يبدو أن الخيارات، على الأقل اختبار تجسس العقود، في الواقع صالح البائع. هذا يشبه إلى حد ما التوقعات الإيجابية للمراكز الطويلة في الأسهم، صناديق الاستثمار المتداولة، أو مؤشر الآجلة، ولكن الخيار خيارات البائع هو أقوى ومستقلة عن اتجاه السوق. قد يفسر جزء كبير من النتائج الإيجابية لأنظمة الخيارات في تداول الكتب. لماذا هناك المشترين الخيار ثم على الإطلاق؟ وغالبا ما يتم شراء الخيارات ليس من أجل الربح، ولكن كتأمين ضد اتجاهات الأسعار غير المواتية من الكامنة. ولماذا هو ميزة البائع لا المحجوبة بعيدا عن أسماك القرش السوق؟ ربما بسبب عدم وجود تداول خوارزمي مع خيارات كثيرة، ولأن هناك على أي حال المزيد من الحيتان من أسماك القرش في الأسواق المالية.


وظائف للخيارات.


يمكننا أن نرى أن تداول الخيارات و باكتستينغ يتطلب بضع وظائف أكثر من مجرد تداول الكامنة. وبدون خيارات، سيتم تخفيض نفس نظام التداول العشوائي إلى هذا السيناريو القصير:


تتطلب الخيارات (على الأقل) ثلاث وظائف إضافية:


يقوم داتالود (1، & # 8221؛ SPY_Options. t8 & # 8243؛، 9) بتحميل بيانات الخيارات التاريخية من الملف & # 8220؛ SPY_Options. t8 & # 8221؛ في مجموعة بيانات. تتضمن بيانات الخيارات ليس فقط أسعار الطلب والعطاء، ولكن أيضا سعر الإضراب، وتاريخ انتهاء الصلاحية، ونوع & # 8211؛ وضع أو الاتصال، الأمريكية أو الأوروبية & # 8211؛ من أي خيار، وبعض نادرا ما تستخدم بيانات إضافية مثل الفائدة المفتوحة. وعلى عكس بيانات الأسعار التاريخية، تكون بيانات الخيارات مكلفة عادة. يمكنك شرائه من البائعين مثل إيفولاتيليتي. ولكن هناك & # 8217؛ s وسيلة بديلة للحصول عليه مجانا، والتي سوف & # 8217 سوف تصف أدناه.


يسرد العمود المركزي أسعار إضراب مختلفة وتواريخ انتهاء الصلاحية، والأجزاء اليمنى واليسرى هي أسعار الطلب والعطاء وأحجام طلبات الشراء للدعوات المخصصة لهم (يسار) ووضع الخيارات (يمين). الأسعار للسهم الواحد. فإن عقد الخيار يغطي دائما عددا معينا من الأسهم، وعادة 100. لذلك يمكنك أن ترى في القائمة أعلاه أنك سوف تحصل على 15 $ قسط عند كتابة خيار دعوة سبي تنتهي في الأسبوع المقبل (03 فبراير 2017) مع 230 $ سعر الإضراب. إذا فاز سبي & # 8217؛ ر فوق $ 230 حتى ذلك التاريخ، و $ 15 هي الربح الخاص بك. إذا كان ريسد إلى 230 $ و 10 سنتا ويتم ممارسة الخيار (يحدث تلقائيا عندما تنتهي في المال)، لا تزال تحتفظ 5 $. ولكن إذا ارتفع فجأة إلى 300 $ (ربما أعلن ترامب جدران جديدة في جميع أنحاء الولايات المتحدة، وكلها تدفع من قبل نفسه)، عليك أن تتحمل خسارة 6985 $.


تعرض الصورة 54 عقدا، ولكن هذا ليس سوى جزء صغير من سلسلة الخيارات، نظرا لوجود العديد من تواريخ انتهاء الصلاحية وأسعار الإضراب المتاحة. سلسلة خيارات سبي يمكن أن تحتوي على ما يصل إلى 10،000 خيارات مختلفة. يتم تحميلها جميعا إلى جهاز الكمبيوتر مع وظيفة كونتراكتيوبديت أعلاه، والتي يمكن أن يستغرق ذلك بضع ثوان لإكمال.


العقد (النوع، 30، برايسكلوز ()) خيارا محددا من سلسلة الخيارات التي تم تنزيلها سابقا. نوع (بوت أو كال)، والأيام حتى انتهاء (30)، والإضراب (برايسكلوس () هو السعر الحالي من الكامنة) هي معلومات كافية لتحديد أفضل خيار المناسب. لاحظ أنه للحصول على أسعار الإضراب الصحيحة في باكتست، قمنا بتحميل بيانات الأسعار الأساسية مع العلم أونادجوستيد. أسعار الإضراب دائما غير معدلة.


بمجرد اختيار العقد، إنتيرلونغ المقبل () أو إنتيرشورت () يشتري أو يبيع الخيار في السوق. إن الشرط إذا () يتحقق من أن العقد متاح وتاريخ انتهاء صلاحيته يختلف عن التاريخ السابق (لضمان تداول العقود المختلفة فقط). حدود الدخول أو التوقف أو الربح سوف تعمل كالمعتاد، فإنها الآن تنطبق فقط على قيمة الخيار، والعلاوة، بدلا من السعر الأساسي. ويفترض باكتست أنه عند ممارسة الخيار أو انتهاء صلاحيته في المال، يتم بيعها مباشرة على الفور، ويتم حجز الربح في حساب المشتري وخصم من حساب البائع. إذا كان الخيار تنتهي من المال، والموقف تختفي فقط. لذلك نحن لا نهتم بالخروج من المواقف في هذه الاستراتيجية. وبصرف النظر عن تلك الاختلافات، فإن خيارات التداول تعمل تماما مثل تداول أي أداة مالية أخرى.


استراتيجيات الخيار باكتستينغ.


هنا & # 8217؛ s طريقة سهلة للحصول على الأغنياء. فتح حساب يب وتشغيل برنامج يسجل سلاسل الخيارات وأسعار العقود في فترات دقيقة واحدة. هذا ما فعله بعض بائعي البيانات في السنوات الخمس الماضية، والآن هم عزيزون بيع كنوز البيانات الخاصة بهم. على الرغم من أنه يمكنك بسهولة دفع عدة آلاف من الدولارات لبضع سنوات & # 8217؛ ق سلاسل الخيارات من الأسهم الرئيسية، وأنا لست متأكدا من الذي يملك حقا حقوق الطبع والنشر من هذه البيانات & # 8211؛ البائع، وسيط، وتبادل، أو المشاركين في السوق؟ قد تكون هذه منطقة رمادية قانونية. على أي حال، تحتاج البيانات التاريخية لتطوير استراتيجيات الخيارات، وإلا لم تتمكن من باكتست لهم.


هنا & # 8217؛ s طريقة للحصول عليه مجانا ودون أي مشاكل قانونية:


هذا السيناريو هو أطول قليلا من البرامج النصية زورو المعتادة أن أشر هنا، لذلك فزت & # 8217؛ ر شرح ذلك بالتفصيل. أنه يولد سلاسل الخيار الاصطناعي لأي يوم من 2018-2017، ويخزن لهم في ملف البيانات التاريخية. يتم احتساب أسعار اخليار من السعر األساسي، والتقلب، ومعدل الفائدة احلالي اخلالي من املخاطر، ومعدل توزيعات األرباح. ويستخدم ثلاثة نطاقات لأسعار الإضراب، وتاريخ انتهاء الصلاحية في أي يوم جمعة من ال 180 يوما القادمة. تحتاج R تثبيت لتشغيله، وأيضا حزمة روانتليب لحساب القيم الخيار. يتم وصف جميع وظائف في دليل زورو. العائد () الدالة ترجع معدل العائد الحالي من أذون الخزانة الأمريكية، و كونتراكتفال () بحساب قسط من خلال حل المعادلة التفاضلية مع جميع المعلمات الخيار. شفرة المصدر لكلا الدوال يمكن العثور عليها في العقد. ج تشمل ملف.


بسبب بطيئة المعادلة التفاضلية حلالا وعدد كبير من الخيارات، السيناريو يحتاج عدة ساعات لإكمال. هنا & # 8217؛ s مقارنة البيانات التي تم إنشاؤها مع بيانات خيارات سبي الحقيقي:


الخط الأزرق هي أسعار الخيار الاصطناعي، والخط الأسود هي الأسعار الحقيقية التي تم شراؤها من بائع بيانات الخيارات، على حد سواء لمدة 3 أسابيع عقود الجاسوس مع 10 نقطة بقعة بقعة الإضراب. يمكنك أن ترى أن الأسعار تتطابق بشكل جيد للغاية. هناك بعض الاختلافات الصغيرة التي قد تكون عشوائية جزئيا، والناجمة جزئيا عن الشذوذ في العرض والطلب. للاستراتيجيات التي تستغل تلك الشذوذ & # 8211؛ والتي تشمل جميع الاستراتيجيات القائمة على التقلبات الضمنية & # 8211؛ أنت & # 8217؛ ليرة لبنانية تحتاج أسعار الخيارات التاريخية الحقيقية. بالنسبة لاستراتيجيات الخيارات التي تستغل فقط تغيرات الأسعار أو تقلب البيانات الأساسية، فإن البيانات الاصطناعية ستفعل على الأرجح. انظر، قراءة هذه المادة حتى النهاية حفظت بالفعل لك بضعة آلاف من الدولارات.


استنتاج.


خيارات وخيارات مجموعات يمكن استخدامها لإنشاء الأدوات المالية الاصطناعية مع خصائص مثيرة جدا للاهتمام. من المرجح أن تكون استراتيجيات الخيارات، وخاصة خيارات البيع، مربحة أكثر من غيرها من الاستراتيجيات. استراتيجيات الخيار الخوارزمي هي قليلا، ولكن ليس أكثر تعقيدا بكثير من الاستراتيجيات مع الأدوات المالية الأخرى.


I & # 8217؛ لقد شملت جميع البرامج النصية في مخزن البرنامج النصي 2017، وأيضا مجموعة البيانات التاريخية مع معدلات العائد (وإلا كنت في حاجة الى جسر كواندل أو زورو S لتحميلها). ستحتاج إلى زورو 1.53 أو أعلى، والذي يتوفر حاليا ضمن & # 8220؛ بيتا & # 8221؛ رابط من صفحة التحميل زورو. رسالة الخطأ من النسخة زورو مجانا حول جسر كواندل غير معتمد يمكن تجاهلها، وذلك بسبب معدلات العائد المدرجة سوف تشغيل البرنامج النصي ومع ذلك.


في المقالة التالية نحن & # 8217؛ ليرة لبنانية ننظر عن كثب في القيم الخيار وفي أساليب الجمع بين الخيارات للحد من المخاطر أو التداول يتراوح السعر التعسفي. تلك المجموعات مع أسماء مضحكة مثل & # 8220؛ الحديد كوندور & # 8221؛ أو & # 8220؛ بوترفلي & # 8221؛ غالبا ما يشار إليها باستراتيجيات الخيارات، ولكنها ليست & # 8211؛ فهي مجرد أدوات مالية مصطنعة. كيف تتاجر بها هو ما يصل الى استراتيجية حقيقية. بعض استراتيجيات الخيار بسيطة، ولكن مربحة باستمرار سيكون موضوع المادة الثالثة من هذه السلسلة المصغرة.


49 أفكار حول & لدكو؛ خوارزمية خيارات التداول 1 & رديقو؛


مادة مثيرة جدا للاهتمام! لدي خيار واحد نظام التداول التلقائي التي تم إنشاؤها من قبل المطورين زورو (عمل عظيم بالمناسبة) وأنه من المهم جدا أن نرى، أن استراتيجيتي يولد نتائج مماثلة لاستراتيجية الخاص & # 8220؛ عشوائي & # 8221؛. وإنني أتطلع إلى المقالات القادمة من هذه السلسلة المصغرة.


أود أن أسأل، هل لديك أي فكرة إذا كان سيتم ترجمة كتابك إلى اللغة الإنجليزية في أي وقت قريب؟ أحب قراءة الكتاب.


أنا & # 8217؛ م مهتمة تماما في هذه المقالات سلسلة مصغرة. واسمحوا لي أن أعرف المقبل واحد من هذه السلسلة.


شكرا & # 8211؛ نعم، ومن المقرر إصدار كتاب الإنجليزية، وأنا فقط يجب أن تجد بعض الوقت لمراجعة الترجمة الخام. أندرس: يمكنك إدخال بريدك الإلكتروني في حقل الاشتراك على اليمين.


مقالة لطيفة، أود أن أسألك ما هي الكتب الجيدة أو حيث يمكنني أن أتعلم التجارة مع الخيارات. شكر.


أنا على حق، رهات تلك الأسعار الاصطناعية والحقيقية تتعلق نوع من & # 8220؛ الاصطناعية & # 8221؛ الخيار الذي تم تقديمه كسلسلة متداولة من الخيارات الحقيقية مع أقرب تاريخ انتهاء الصلاحية وتغيير الإضراب ديناميكيا (اعتمادا على السعر الأساسي)؟


إنفستوبيديا و تاستيتريد لديها بعض الدروس ومقاطع الفيديو حول الخيارات. - انها لا تدحرجت على سلسلة، ولكن سلسلة الخيار مع ضربات مختلفة وتاريخ انتهاء الصلاحية، تماما كما هو الحال في الحياة الحقيقية. وإلا فإن الاختبار الخلفي لن يكون واقعيا.


عندما تقوم بمقارنة الأسعار الاصطناعية بالأسعار الحقيقية، هل تستخدم إضراب أجهزة الصراف الآلي؟ النقطة الكاملة، بالنسبة لي، من باكتستينغ استراتيجية التداول الخيار مقابل البيانات الخيار الحقيقي هو أن في الأجنحة سوف يكون ضمنيا أكثر بكثير من تلك التي ولدت بشكل مصطنع.


كانت الضربات المستخدمة حوالي 10 نقاط إيتم.


نشكرك على نشر هذه المقالة المثيرة للاهتمام. هل لي أن أعرف متى سيتم نشر المادتين الأخريين من هذه السلسلة المصغرة؟


عندما أحصل على بعض الوقت & # 8230؛ 🙂


ما المادة لطيفة! تبدو نتائج نظام التداول العشوائي مشابهة لمؤشر كبوي S & أمب؛ P 500 بوتوريت ومن المنطقي.


شكرا جزيلا على هذا المقال! كان مجرد التفكير في هذا في اليوم الآخر.


أنا أحب هذا بلوق & # 8217؛ ق المقالات كثيرا. أنا أتداول حاليا 1 سنة انتهاء خيارات المكالمة من أسهم محددة.


مشكلتي الأكبر مع & # 8220؛ ميزة البائع & # 8221؛ أنه يتناقض مع & # 8220؛ المخاطر التي تسيطر عليها & # 8221؛ بيان.


& # 8220؛ شيء غالبا ما يخلط بين المستثمرين هو ما إذا كان أو لم يكن قصيرة مكالمة وطويلة وضعت هي نفسها. بشكل حدسي، وهذا قد يجعل بعض الشعور، منذ المكالمات ويضع العقود المقابلة تقريبا، ولكن يجري قصيرة مكالمة وطويلة وضع ليست هي نفسها. عندما كنت طويلة وضعت، لديك لدفع قسط وأسوأ حالة سيؤدي إلى فقدان فقط قسط. ومع ذلك، عندما كنت قصيرة مكالمة، يمكنك جمع قسط الخيار، ولكن كنت تتعرض لكمية كبيرة من المخاطر & # 8221؛


لذلك عندما تكتب (عارية) يدعو خطر الخاص بك هو غير محدود. فترة انقضاء قصيرة (30 يوما) هو يوفر لك في معظم الحالات، ولكن هذا هو الوهم الذاتي. هذه الطريقة هي مشابهة جدا لعمليات احتيال التداول السير، حيث 99،5٪ من البوتات الوقت الفوز قليلا (e. g قسط المكالمة) مبلغ من المال، ولكن عندما كنت فضفاضة، وكنت خطر كمية كبيرة من المال الخاص بك.


نداء طويل أو وضع خطر التجار محدودة ويختارون من خارج المال الخيارات لمضاعفة أرباحهم وموازية أنها تقلل من فرصة الفوز.


وأود أن تكون مهتمة في ليبس (1+ سنة انتهاء الصلاحية طويلة / خيارات وضع) باكتست.


افعل ذلك. تحميل زورو 1.54 من منتدى المستخدم، باكتست نظام مع ليبس. لهذا تحتاج إلى زيادة & # 8220؛ دايسماكس & # 8221؛ متغير في بيانات توليد البيانات النصية أعلاه إلى 1 سنة (365) أو 2 سنة (2 * 365) لتضمين عقود طويلة الأجل. سيحتاج البرنامج النصي بعد ذلك إلى مزيد من الوقت لتوليد البيانات.


منذ خيارات التداول هي ميزة زورو جديدة، أنا & # 8217؛ متساءل إذا كان الجزء أبي الوسيط من دليل (زورو التاجر / دليل / إن / brokerplugin. htm) تم تحديثها بما فيه الكفاية لحساب خيارات المناولة.


أنا & # 8217؛ م يسأل لأنني & # 8217؛ م تحاول كتابة البرنامج المساعد دل ل تراديكينغ (قريبا ليتم تسميته إلى ألي انفست). لديهم مخزونات، صناديق الاستثمار المتداولة، وعقود الخيارات. منخفضة جدا حاجز إلى دخول وسيط كذلك ($ 0 المطلوبة للحصول على الوصول أبي).


بالنسبة للخيارات، قم بتنفيذ وظائف أبي الأساسية بالإضافة إلى 5 وظائف بروكيركوماند: GET_POSITION و GET_OPTIONS و GET_UNDERLYING و SET_SYMBOL و SET_MULTIPLIER.


المادة رائعة، وذلك بفضل لتقاسم، حاولت من التعليمات البرمجية وتحميل البيانات الخيارات عن طريق البرنامج النصي، يبدو كل شيء لتحميل موافق وجعل لي ملف T8 48MB ل سبي ولكن عندما تشغيل البرنامج النصي عشوائي أنا & # 8217؛ ر الحصول على أي الصفقات. في المرة الأولى لقد ركض زورو (I & # 8217؛ م على أحدث إصدار تم تحميلها منذ 3 أيام) حتى حقا غير متأكد ما أنا & # 8217؛ م فعل خاطئ.


أي مساعدة سيكون موضع تقدير وأنا حقا نتطلع إلى الحلقة القادمة في هذه السلسلة آسر 😉


هنا هو إخراج السجل:


خيارات الاختبارسيلراندوم سبي.


أسيت أكونت أسيب.


فترة البار 24 ساعة (متوسط ​​2233 دقيقة)


فترة الاختبار 12.01.2018-01.06.2018 (1270 بار)


فترة الاستعادة 80 بارات (16 أسبوعا)


وضع محاكاة واقعية (الانزلاق 5.0 ثانية)


انتشار 2.0 نقطة (لفة 0.00 / 0.00)


العقود لكل لوت 1.0.


إجمالي الربح / الخسارة 0.00 $ / -0.00 $ (-1p)


متوسط ​​الربح 0.00 $ / السنة، 0.00 $ / الشهر، 0.00 $ / اليوم.


ماكس دراون -0.00 $ -1٪ (مي -0.00 $ -1٪)


إجمالي الوقت المنخفض 0٪ (تاي 0٪)


الحد الأقصى للوقت 0 دقيقة من سبتمبر 2018.


أقصى هامش مفتوح 0.00 $


الحد الأقصى للمخاطر المفتوحة 0.00 $


حجم التداول 0.00 $ (0.00 $ / يار)


تكاليف المعاملة 0.00 $ سبر، 0.00 $ سلب، 0.00 $ رول.


رأس المال مطلوب 0 $


عدد الصفقات 279 (52 / سنة، 1 / ​​أسبوع، 1 / ​​يوم)


النسبة المئوية للفوز 0.0٪


الحد الأقصى للفوز / الخسارة 0.00 $ / & # 8211؛ 0.00 $


متوسط ​​أرباح التجارة 0.00 $ -1 $ p (+ 0.0p / -1. $ p)


متوسط ​​انزلاق التجارة 0.00 $ 1. $ p (+ 0.0p / -1. $ p)


متوسط ​​قضبان التداول 23 (+0 / -23)


أقصى قضبان تجارية 26 (5 أسابيع)


الوقت في السوق 506٪


ماكس الصفقات المفتوحة 6.


أقصى خسارة متتالية 279 (غير مترابطة 279)


العائد السنوي 0٪


نسبة شارب 0.00.


معيار كيلي 0.00.


R2 معامل 1.000.


مستوى الثقة أر دماكس كابيتال.


تحليل محفظة أوبتف بروف فوز / خسارة وغت٪


ومقتطف من ملف السجل & # 8230؛


[1338: فري 13.05.16 19:00] +0 +0 6/271 (206.21)


[سبي :: SC1272] اتصل 20180513 204.0 0@3.5713 غير متداولة اليوم!


[سبي :: SC1272] منتهي الصلاحية 1 اتصل 20180513 204.0 0 @ 207: +0.00 أت 19:00:00.


[1339: مون 16.05.16 19:00] +0 +0 5/272 (204.96)


[1340: الثلاثاء 17.05.16 19:00] +0 +0 5/272 (206.46)


[1341: ويد 18.05.16 19:00] +0 +0 5/272 (204.44)


[1342: ذو 19.05.16 19:00] +0 +0 5/272 (204.06)


[سبي :: SC4278] ورايت 1 كال 20180624 205.0 0@3.4913 أت 19:00:00.


[1343: فري 20.05.16 19:00] +0 +0 6/272 (204.92)


[سبي :: SP1773] وضع 20180520 208.0 0@4.2851 لا تداول اليوم!


[سبي :: SP1773] منتهية الصلاحية 1 ضع 20180520 208.0 0 @ 204: +0.00 أت 19:00:00.


[1344: مون 23.05.16 19:00] +0 +0 5/273 (205.51)


[1345: الثلاثاء 24.05.16 19:00] +0 +0 5/273 (206.17)


[1346: ويد 25.05.16 19:00] +0 +0 5/273 (208.67)


[1347: الخميس 26.05.16 19:00] +0 +0 5/273 (209.44)


[سبي :: SC4779] ورايت 1 كال 20180701 209.0 0@3.7358 أت 19:00:00.


[1348: الجمعة 27.05.16 19:00] +0 +0 6/273 (209.53)


[سبي :: SP2274] وضع 20180527 208.0 0@3.3622 لا تتداول اليوم!


[سبي :: SP2274] منتهية الصلاحية 1 ضع 20180527 208.0 0 @ 209: +0.00 أت 19:00:00.


[1349: الثلاثاء 31.05.16 19:00] +0 +0 5/274 (210.56)


[سبي :: SC2775] الغلاف 1 اتصل 20180531 207.0 0@2.2309: +0.00 في 19:00:00.


[سبي :: SC3276] كوفر 1 كال 20180531 205.0 0@5.1843: +0.00 أت 19:00:00.


[سبي :: SP3777] الغلاف 1 ضع 20180531 206.0 0@0.8602: +0.00 في 19:00:00.


[سبي :: SC4278] كوفر 1 كال 20180531 205.0 0@4.9463: +0.00 أت 19:00:00.


[سبي :: SC4779] كوفر 1 كال 20180531 209.0 0@2.8347: +0.00 أت 19:00:00.


[1350: ويد 01.06.16 19:00] +0 +0 0/279 (209.12)


أرى أن يتم فتح جميع المواقف مع حجم صفر، كما لو كنت قد حددت عدد العقود إلى 0. هل استخدمت البرنامج النصي غير المعدل من مستودع؟


أنا & # 8217؛ م باستخدام ملف OptionsSimulate. c مباشرة من ملف مضغوط.


لقد قمت بتثبيت R ومكتبات كوانتليب وجسر R يبدو أن تعمل بشكل جيد كذلك.


الجزء العلوي من الملف.


سترينغ فلنام = & # 8220؛ هيستوري \\ SPY_SimOptions. t8 & # 8221 ؛؛


فار ستريكيماكس [3] =؛ // 3 نطاقات ضربة مع خطوات مختلفة.


فار ستريكستيب [3] =؛ // ستيبويدثس للنطاقات الثلاثة.


إنت دايسماكس = 180؛


فار بيداسكسبريد = 2.5؛ // عرض التسعير / الطلب في المئة.


فار ديفيدند = 0.02؛


إنت تايب = 0؛ // أور أوروبية، أو فيوتشر.


لوكباك = 21؛ // للتقلب.


أنا & # 8217؛ م آسف للأسئلة n00b، وأدواتها للاهتمام حقا وأنظمة وكنت أرغب في محاولة الخروج بعض ينتشر الائتمان الرأسي باستخدام هذا الرمز كأساس على سبي وربما بعض الصكوك الأخرى!


انها ليست مسألة مستجد، بل هو في الواقع خطأي. أرى فقط أنني & # 8217؛ نسي لضبط خيارات مضاعف في البرنامج النصي. هذا لا يهم مع النسخة زورو السابقة منذ المضاعف كان 100 افتراضيا، ولكن يجب الآن تعيين لأن الخيارات يمكن أن يكون مضاعفات مختلفة جدا.


I & # 8217؛ لقد صحح النص البرمجي أعلاه. شكرا لإعلام لي!


نعم كان ذلك!


الحصول على نتائج العودة الآن، وذلك بفضل جزيلا لمساعدتكم جكل.


أنا & # 8217؛ م الآن لوضع 1MM $ في حساب وتجارة هذا الطفل 😉


هل لديك أي فكرة عندما سوف تحصل على العمل على بقية المواد في هذه السلسلة؟


يبدو أن الرمز أدناه لا يعمل بعد الآن.


يتكامل ملف كسف SPY. csv مع هذا المحتوى:


QECx05، عنوان ورل الذي طلبته غير صحيح. الرجاء استخدام عنوان ورل التالي بدلا من ذلك: / أبي / v3 / داتاسيتس /: database_code /: dataset_code.


عذرا، في الواقع كان هذا الملف من كواندل، وتحتاج إلى اشتراك مدفوع.


من ياهو أحصل على الخطأ يمكن & # 8217؛ ر تحميل سبي من ياهو.


أي شخص لديه نفس المشكلة؟


أعتقد أن كلهم ​​يواجهون نفس المشكلة، حيث غيرت ياهو بروتوكولها الأسبوع الماضي. إذا واجهت مشاكل من هذا القبيل، والبحث عن حل ليس فقط على بلدي بلوق، ولكن لأول مرة في منتدى زورو:


شكرا لكم على هذه المعلومات المفيدة عن أنظمة التداول الآلي!


أنا & # 8217؛ م جميلة جديدة لهذا ولكن أعتقد أن هذا هو صفقة أكبر بكثير مما جعله الصوت:


وGT. هناك بعض الاختلافات الصغيرة التي قد تكون عشوائية جزئيا، والناجمة جزئيا عن الشذوذ في العرض والطلب. بالنسبة للاستراتيجيات التي تستغل تلك الحالات الشاذة ستحتاج إلى بيانات تاريخية حقيقية.


وجود تقلب دقيق ضروري. وبدون ذلك، أنت لست مجرد كتابة استراتيجية لا تستغل تلك الحالات الشاذة، فأنت تكتب واحدة تتجاهلها تماما. انها قابلة للمقارنة لتوليد سعر السهم عن طريق اختيار رقم عشوائي على أساس توزيع الاحتمالات في الأسابيع السابقة & # 8217؛ أسعار أو تمهيد جميع أكبر التحركات.


تستند أسعار الخيارات إلى التوقعات حول المستقبل ولكن (ما لم أسيء فهم شفرتك)، فإنك تقوم بتسعيرها استنادا إلى الماضي. سوف تكون الاختلافات أكثر وضوحا على أوندرلينجس غير سبي، وخاصة حول وقت الأرباح (يقول آبل، مسفت أو غوغ).


وأجد أيضا صعوبة في التفكير في استراتيجية لا تستغل الفرق بين التقلب الضمني والفعلي. حتى دلتا 16/5 وضعت انتشارا على سبي يعمل فقط وكذلك لأنه لأن الرابع هو أعلى بكثير مما ينبغي أن يكون.


نعم، التغييرات سعر الخيار بسبب توقع تقلب، ربما عندما نهج أخبار الشركة، ينتمي إلى الشذوذ المذكورة. القاعدة العامة هي: بالنسبة للشذوذ التي لها أيضا تأثير على الكامنة يمكنك استخدام الأسعار الاصطناعية. بالنسبة إلى الحالات الشاذة التي تؤثر فقط على الخيارات، ولكن ليس العناصر الأساسية، ستحتاج إلى شراء بيانات خيارات تاريخية حقيقية.


كيف جيدة أن تكون البيانات محاكاة إذا كنت سوف تغيير باربيريود = 1440 ليكون باربيريود = 1؟


نظريا، جيدة أو سيئة كما البيانات اليومية، لأن المبدأ هو نفسه. ولكن لم أجد بعد اختبارات مع 1 دقيقة خيارات البيانات. هذا & # 8217؛ s فظيع الكثير من البيانات.


& # 8220؛ بسبب بطء المعادلة التفاضلية حلالا وعدد كبير من الخيارات، السيناريو يحتاج عدة ساعات لإكمال. & # 8221؛


كم أسرع هل تعتقد أن هذا يمكن أن يكون إذا تم استبدال الأشياء R / كوانتمود C / C ++؟ أنا & # 8217؛ م التفكير في توليد الكثير من البيانات الاصطناعية.


أعتقد أنه _is_ C ++، على الأقل كوانتليب الكامنة مبرمجة في C ++. و R على علوي وربما لا تذكر. المشكلة ليست رمز، ولكن الرياضيات. حل المعادلات التفاضلية عدديا بطيئة. بلاك سكولز أسرع بكثير، ولكن للخيارات الأوروبية فقط. إذا كان لديك الكثير حقا من البيانات لتوليد، قد يكون من المنطقي للتحقق من سرعة أساليب تقريب مختلفة للخيارات الأمريكية.


لاحظت تقلب ثابت في 20 في السيناريو أعلاه لتوليد أسعار الخيار الاصطناعية. قد لا يكون هناك حجة لتقلب لتكون المتداول 30 يوما وتحسب بشكل منهجي من الكامنة؟


ماذا تعني مع & # 8220؛ المتداول 30 يوما & # 8221 ؛؟ 20 هي فترة التقلب المعتادة في الحسابات المالية، لأنها تعادل تقريبا شهر واحد. 30 ربما لن يحدث فرقا كبيرا.


يمكنك استخدام تقدير مرة واحدة من التقلب أعتقد: على سبيل المثال 16 ل S & أمب؛ P. ولكن على أساس متجدد فإنه سيكون على نطاق واسع جدا والذي هو بالطبع جزء من السبب في أسعار الخيارات تتغير كثيرا: كما ترتفع التقلبات حتى يفعل سعر الخيار. إذا كنت تستخدم المتوسط ​​المتحرك لمدة 20 يوما (أو 30) المتداول سوف تحصل على أسعار خيار تركيبية أكثر دقة من مجرد افتراض شقة واحدة لمرة واحدة 16 ل S & أمب؛ P عندما تكون في بعض الأحيان الفعلية قد تكون 10، وأحيانا 30. لم أكن نظرت في العمارة زورو وذلك دون & # 8217؛ ر الآن ما إذا كان معظمها ناقلات، أو نظرة أو ما. وفي كلتا الحالتين سيكون من الممكن تضمين المتوسط ​​المتحرك لليوم ذي الصلة لتقلب الأداة الأساسية بدلا من الرقم الثابت.


ولكن هناك مرة أخرى هذا هو ما تفعله ربما؟ هيستفولوف = فولاتيليتيوف (20) & # 8211؛ ربما هذا هو 20 يوما؟ لا 20٪؟


سؤال ليس بيانا.


على أي حال يبدو قطعة رائعة من البرمجيات. مجرد الذهاب إلى محراث في طريقي من خلال دليل.


نعم، يبدو فول هو سلسلة زمنية. آسف لإزعاجك.


نعم، انها تقلب سنوي من 20 يوما الماضية. إذا كانت 20٪، كنت قد كتبت: هيستفولوف = 0.2.


كلا. فإنه لا & # 8217؛ ر قطع عليه. لا يمكنك استخدام مقياس واحد للتقلب التاريخي لكل شيء بدءا من خيار شهر واحد إلى انتهاء صلاحية 24 شهرا. ولعل المخطط بأكمله غير صالح. على سبيل المثال إيف لمدة سنتين سبس يبلغ حاليا 15٪ + في حين أن خيار تنتهي في الأيام القليلة القادمة هو 5٪ إيش.


قد يكون غير صالح لاستخدام البيانات المصنعة على الإطلاق. إلا إذا كنت التعامل معها كنوع من اختبار مونت كارلو: هذا هو ما قد / كان يمكن أن يحدث / قد يحدث.


أنتوني، السيناريو هو حساب السعر الحالي للخيار. السعر الحالي يعتمد على التقلبات الحالية. ليس على التقلبات منذ 24 شهرا.


يمكنك حساب قيمة الخيارات الأوروبية مع صيغة بلاك سكولز، والخيارات الأمريكية، كما هو الحال في السيناريو أعلاه، مع طريقة التقريب. كلا الأسلوبين عادة استخدام 20 يوما تقلب. طريقة أخذ العينات التقلب يمكن أن تختلف، ولكن 20 يوما هي شائعة جدا لجميع برامج التداول الخيارات التي أعرفها. ويمكنك أن ترى من المقارنة مع الأسعار الحقيقية فوق أن هذه الفترة يعمل بشكل جيد إلى حد ما.


لا، لا يمكنك حساب السعر الحالي للخيار في أي يوم معين بهذه الطريقة. لا توجد طريقة لإعادة إنتاج تقلبات ضمنية بدقة وبالتالي السعر في أي تاريخ معين في الماضي. وهذا هو التقلب الضمني نحن مهتمون، وليس التاريخية. وأنا أتفق تماما على بلاك سكولز بطبيعة الحال واستخداماته ولكن هو عربة قبل الحصان إلى توقع لتوصيل في 20 تقلب اليوم كما في 3 يناير 1985 ونتوقع منه أن يأتي بسعر دقيق كما تداول في الإغلاق في ذلك اليوم ل سبس لأي إضراب معين أو انتهاء الصلاحية.


انها تبحث في الطريق الخطأ حول.


ما يمكنك أن تحاول أن تلعب حولها مع أساليب مختلفة لتقدير ما قد يكون ضمنا المجلد / السعر في 3 يناير 1985 لإضراب معين وانتهاء خيار سبس.


على سبيل المثال قد تستخدم التقلبات التاريخية لمدة 5 أيام لخيار تنتهي في أسبوع و 252 يوم تقلب لخيار تنتهي في السنة. أو قد تنطوي على تقلبات من خلال النظر في مصطلح هيكل العقود الآجلة فيكس من عام 2004. أو على الأقل استخدام مؤشر فيكس نفسه يعود إلى عام 1986 كمدخلات لتقلب 30 يوما.


ومهما فعلت، فلن تنجح في إنتاج أي شيء مثل ما تم تداوله فعليا في اليوم. أو على الأقل ليس بشكل ثابت ودقيق على جميع حالات الإنتهاء والإضرابات.


وأعتقد أن العملية التي تصفها لها قيمة، ولكن نتيجة كل من الأسعار المنتجة والاختبارات الخلفية الناتجة عنها ستكون أقرب إلى عملية كارت موت عشوائية من إلى اختبار الظهر على بيانات الأسعار المتداولة الفعلية.


وأعتقد أنها عملية قيمة ولكن ما ينتج هو سلسلة من الأكوان المتوازية: ما يمكن أن يحدث لاستراتيجية معينة على مدى فترة معينة من الزمن باستخدام التقلبات الضمنية التي قد تكون أو لم يتم تداولها.


آسف أن تكون طويلة ينضب وأنا معجب كل من المنتج الخاص بك والنص أعلاه. لم أكن قد فكرت في توليد أسعار الخيار وهمية لم أكن رأيت المادة ممتازة.


ولكن في رأيي على الأقل تحتاج إلى إعادة النظر في المدخلات الخاصة بك في صيغة بس بقدر التقلب هي المعنية.


وبالمناسبة يرجى أن تدرك جيدا أن معجب المنتج الخاص بك وأفكارك. دون & # 8217؛ ر تخيل أنني أصعب. وبالمثل يرجى عدم & نبسب؛ & نبسب؛ & نبسب؛ تصور أعتقد أنني & # 8220؛ الحق & # 8221؛!


أنا فقط الاستمتاع رحلة والحوار معكم، ونأمل معا يمكننا تحسين بعضنا البعض & # 8217؛ ق فهم هذا الموضوع.


الألغام محدودة!


قل التاريخ الذي تبحث عنه في 7 يناير 1987. في ذلك اليوم كان تقلب سبس التاريخي المحسوب على مدى 20 يوم تداول 15.23. وكانت التذبذبات التاريخية في ذلك اليوم خلال الأيام ال 252 الماضية هي 14.65.


لمدة 5 أيام كان 18.


الآن أقول إنني أحاول & # 8220؛ حساب & # 8221؛ (تخمين) السعر (الذي قد يكون تم تداوله في 7 يناير 1987) لخيار تنتهي في 5 أيام، 20 يوما و 252 يوما. دعونا نفترض أتم.


My suspicion is that it would not be helpful to use 15.23 for all three expiries.


شكرا لك على كلماتك الرقيقة. Finance is complex. My knowledge is even more limited and I’m daily surprised by some results that I didn’t expect. & # 8211؛ In your example, the 15.23% volatility is the correct value. If you used a higher volatility period for higher expiration, then it depends on whether it’s still annualized volatility or just volatility of a longer time. In the latter case the results are off by some factor, in the former case they are based on too old volatility and thus not up to date. & # 8211؛ You’re right about the implied volatility, since it is affected by the difference of theoretical and real option value. So you cannot use the script above for getting it. Otherwise you would just get back some approximation of the current volatility. You need real option prices for IV.


I hope that it’s alright that I discuss this with just a few of my clientele, this will assist.


Scenario analysis and trading options using R.


I present you with my restructured project on options trading and scenario analysis. You are more than welcome to try it out. Firstly, I will give a small presentation that will reveal what you can do with it and whether you need to continue reading. Then I will continue with dependencies, classes used and classes created along with methods defined. Finally, I will give some basic operations to show how you can use it yourself.


Lets say you are constructing a portfolio. You want to start with risk-reversal strategy(buy call high, sell put low). You are interested in payoff chart:


For some reason you decide to short a stock and add it to your portfolio:


You now realise that you must really have negative view on the market to trade this. You decide that this will be your view, but your neighbour tells you that a sharp price increase is possible. Decide to buy some digitals:


You are satisfied with your decisions and would like to check you profit and loss as up to now numbers on z axis just showed payoff. Remember as you shorted the stock, you’ve got some cash. In particular 100. But your digitals cost and sum of option prices should be slightly positive as both symmetrically out of the money:


While you are very happy with your decisions you also want to investigate some sensitivities. Say vega:


Now you’re like:”Not trading this weird thing”.


If you liked what you saw and you want to try it yourself or even contribute, continue reading.


“sa_work. R” is the file where you would normally work. It has only 1 line to call all you need:


This is the only line you need to change once you have repository downloaded. Just locate “0_sa_init. R” and it will do all. And by all I mean 2 things: load packages, load other scripts and couple of basic parameters.


“quantmod” might be needed if you want to download some option or stock data from yahoo. “RQuantLib” is not currently used, but pricing functions might be taken from it later to price americans. “fields” was used in earlier version for interpolation over scatter and might be needed in later development. “rgl” – 3d graphics. “lubridate” is not essential, but it makes life easier when working with dates at user level. However all date objects are automatically converted to “timeDate” class.


File structure is simple:


“0_funs” folder with 2 scripts loaded from it “0_basic. R” that contains some basic functions – only 2 out of 5 are really needed. And “0_inst. R” – abbreviation for instruments, but now contains all the project within. Surprisingly only 500 lines of code. Went down twice after I drifted to OOP approach.


“2_structure_int. R”, “2_structure_vol. R” will be used for interest rate structure and implied volatility surface implementation in the future and are currently not used.


Classes used are S4 for outputs, some simple variables that needed formalisation and parameter objects. Reference classes are used for instruments.


“currency” inherits from “character” and Currency() function makes sure its of length 3 and creates new.


“gen. par” contains number of preferred working days in a year and list of interest rates.(later could be extended to interest rate structure).


“stock. par” contains all parameters that are stock specific and varies over time.


“scatter” inherits from “matrix”. Contains output from reference classes: data, row and column variables.


“security” superclass of all securities.


“spot”, “forward” and “option” inherits from “security”.


All of them have same methods: price, delta, gamma, theta, rho, rhoQ, vega. All of them have arguments: st(stock price), tVec(time), vol(volatility). “option” class has additional method: getiv.


Here is the list of functions you need:


time_seq(from, to, by = “hour”, rng = c(9, 16), holiday = holidayNYSE(2018:2020), trading = TRUE)


– creates time sequence. All methods round the time to hourly so don’t use higher frequency! Also, avoid using daily, just stick to default until you know what you are doing.


GenPar() – creates “gen. par” object named “gen. par” and assigns it to “gen. par” environment.


lsg() gets you gen. par object.


StockPar() – analogous to GenPar, just names it paste0(ticker,”.par”)


lss() – lists objects in “stock. par” environment.


rms() – clears “stock. par” environment.


Spot(id, num=1, class=”equity”, cur=”usd”),


Forward(id, underlying, maturity, K, num=1, class=”equity”, cur=”usd”),


Option(id, underlying, maturity, K, put, ame=0, type=”vanilla”, num=1, extra=list(0), class=”equity”, cur=”usd”)


– creates security objects and assigns it to “securities” environment.


lsi() – lists objects in “securities” environment.


rmi() – clears “securities” environment.


vaSecurities() – collects all objects in “securities” environment in a list.


أخبار جيدة. this is all you need. Few things to note. All strings are converted to CAPS including object names for instruments. Only security class is equity. Only 2 option types are available: “vanilla” and “binary”(cash-or-nothing). All options are european.


Try it out. Your opinions on flaws, mistakes or improvements are more that welcome.


خيارات.


96 пользователей находятся здесь.


МОДЕРАТОРЫ.


برازيو دوغل أوبتيونس برو о команде модераторов & راكو؛


مرحبا بكم في رديت،


الصفحة الأولى للإنترنت.


والاشتراك في واحدة من الآلاف من المجتمعات المحلية.


отправлено & # 32؛ 1 день назад автор cenie.


помощь правила сайта центр поддержки вики реддикет مود غدلينس связаться с нами.


приложенияи инструменты رديت لأيفون رديت لالروبوت موقع الجوال кнопки.


Использование данного сайта означает، что вы принимаете & # 32؛ пользовательского соглашения & # 32؛ и & # 32؛ Политика конфиденциальности. &نسخ؛ 2018 ريديت инкорпорейтед. Все права защищены.


يتم تسجيل ريديت وشعار ألين علامات تجارية مسجلة لشركة رديت إنك.


وبي. Rendered by PID 1594 on app-336 at 2018-01-25 23:32:44.013086+00:00 running b7722f3 country code: UA.


Algorithmic Trading in R Tutorial.


In this post, I will show how to use R to collect the stocks listed on loyal3, get historical data from Yahoo and then perform a simple algorithmic trading strategy. Along the way, you will learn some web scraping, a function hitting a finance API and an htmlwidget to make an interactive time series chart.


For this post, a trading algo is defined as a set of rules that trigger a buy or sell event rather than a predictive model or time series forecast. This is the simplest type of trading algo, but if you are interested in digging deeper into finance with R, I would encourage you to take DataCamp’s course in modelling a quantitative trading strategy in R.


خلفية.


In 2018, I started investing a little at loyal3. Their service is unusual and a great place to start your investment journey. Rather than charge the investor for trades, loyal3 charges the companies to list on their platform. The premise is that people who like a company’s service would also buy the stock and in doing so become strong brand advocates. Making the platform more compelling is that you can buy fractional shares. So, you can get into that $800 amazon stock for only $10 and buy another $10 fraction each time you have a bit of extra cash at the end of the month. Sure there are friction costs since you have to trade in windows and your entire portfolio is limited to.


70 stocks but loyal3 represents a fun and low cost way to explore equity training. You can put real skin in the game for as little as $10 !


To be clear, I have the typical retirement and investment accounts but I like loyal3’s clean interface on the app and the lack of fees. I end up checking my fun loyal3 portfolio more often than my mutual funds simply because it is easy and amusing to see the performance of the stocks I directly picked.


The stocks that are available at loyal3.


Setting Up Your Workspace.


To start, load the libraries into your environment. I almost always use rvest for web scraping these days. There are other packages that work including RSelenium , but I like how easy rvest can be executed.


The second package, pbapply , is optional because it simply adds a progress bar to the apply functions. Since you could be scraping hundreds of web pages a progress bar can be helpful to estimate the time.


Next, TTR is a package that I just started to explore. The library is used to construct “Technical Trading Rules”. Although you will learn a simple trading algo in this post, the TTR package can perform more sophisticated calculations and is worth learning.


The dygraphs library is a wrapper for a fast, open source JavaScript charting library. It is one of the htmlwidgets that makes R charting more dynamic and part of an html file instead of a static image. Lastly, the lubridate package is used for easy date manipulation.


Data Collection.


All the loyal3 stocks are all listed on a single page. Before you can look up individual daily stock prices to build your trading algorithm, you need to collect all available stocker tickers. The first thing to do is declare stock. list as a URL string. Next use read_html() so your R session will create an Internet session and collect all the html information on the page as an XML node set. The page CSS has an ID called “pany-name”. Use this as a parameter when calling html_nodes() to select only the XML data associated to this node. Lastly, use html_text() so the actual text values for the company names is collected.


To examine the stocks that are available on loyal3, you can print the stocks. names object to your console. This returns the company name as a text vector.


In order to research the stock prices, you need to get the ticker symbol first. When you are on the loyal3 site, you can click on the company tile to load a page with a ticker symbol and other company information.


Using html_nodes() on stocks, you pull all nodes marked with an “a. ” In HTML the <a> tag defines a hyperlink which is used to link form one page to another. Within the hyperlink tag, the “href” refers to the exact URL address. So html_attr() will extract the URL for ALL links on the page if you pass in “href”.


After doing some manual inspection, I found the 54th to 123rd links on the page represent the company pages I need in order to scrape the ticker information. The last line uses paste0() to concatenate the base URL string ’loyal3` to the specific company pages, like “/WALMART”. For example, loyal3/WALMART:


On each of the company pages there is a description, a recent closing price and the ticker. All company pages are organized the same so the custom function get. ticker() can be used to extract the ticker symbol.


Within a company’s web page there is a table called “ticker-price”. The function will navigate to a company page, identify the appropriate table, extract the text with html_text() . Lastly, using sub() along with the regular expression ^([[:alpha:]]*).* and \\1 will retain all alphabetical characters. The result is that the any special characters, like $, and any numeric characters, like the closing price, are removed. As the function reads each of the 70 pages, it will only collect the stock ticker.


the loyal3 stock page for Alibaba, where you see the table containing the stock’s ticker, BABA, is below the bolded text.


Armed with your custom function, use pblapply() to apply it to each of the stock. links which contain each company’s page. The resulting object, stock. tickers , is a list of individual stock tickers with each element corresponding to an individual company.


One way to change a list of elements into a flat object is with do. call() . Here, you are applying rbind to row bind each list element into a single vector. Lastly, you create a data frame with the symbol and company name information.


To be consistent in your analysis, you may want to limit the amount of historical information you gather on each stock. The Sys. Data() function will store a date object as year, month and then day. Using years with an integer is one way to subtract a specific amount of time from the start. date object.


To get the Yahoo finance data, the date object has to be changed to simple character objects without a dash. Using the global substitution function gsub() on both start. date and end. date will change the class and simultaneously remove dashes. Within gsub() , pass in the character pattern to search for, then the replacement characters. In this case the replacing pattern is an empty character in between quotes. The last parameter is the object that gsub() will be applied to.


The TTR() function getYahooData() accepts a stock symbol, and a starting and ending date. The function returns a data frame that has time series information. Each row is a date and the columns contain information such as the “Open”, “High”, “Low” and “Closing” price for an equity. Since you are looking up multiple companies, you can use lapply() or pblapply() . Pass in the vector of company symbols, then the function, getYahooData() , and then the date information. The date objects are recycled parameters each time getYahooData() is applied to a stock symbol.


To make selecting the returned list, stocks. ts , easier to navigate you can add names to the list elements. Using names with the stocks. ts object declare the names as the original $symbol vector.


When working with large lists, I like to examine the resulting object to make sure the outcome is what I expected. Now that the elements have names, you can reference them directly. In this example, you are examining the first 6 rows for AMC Entertainment Holdings (AMC). Using head() on the list while referencing $AMC will return a portion of the time series for this stock:


Examining the Stock Data.


When I listen to financial news commentators often refer to charts. Despite high frequency trading and active management performed by others, many small investors still refer to charts to gain insight. The time series object can be quickly displayed using plot. Pass in the list referring to the named element such as $AMC and then the column you want to display, here $Close .


The preceding plot is static and not very interesting.


Let’s use a JavaScript library to make a chart you can explore. In this code snippet, you may observe the “%>%” or pipe operator. The pipe operator is a good way to write concise code. It forwards an object to the next function without forcing you to rewrite an object name like you did earlier in this post.


In this example, you create a dygraph referring to the Twitter stock, $TWTR , and then the column you want to plot, $Close . Within dygraph, main adds a title that is specified in between the quotes. Using the “%>%” this entire object is forwarded to the next function dyRangeSelector() . You can specify a default date range using c() with a start and end date string. The resulting HTML object is a dynamic time series for Twitter’s stock with a date slider at the bottom.


Remember, to change the equity displayed, change the ticker symbol in the stocks. ts list and then the graph title.


This is a basic dygraph for Twitter’s stock.


A Simple Trading Strategy: Trend Following.


High frequency traders and hedge funds use sophisticated models and rules based approaches to execute trades. If you want to learn more I suggest visiting quantopian for advanced approaches. For simpler approaches start with this page at Investopedia.


In the code below, you will visualize a simple momentum trading strategy. Basically, you would want to calculate the 200 day and 50 day moving averages for a stock price. On any given day that the 50 day moving average is above the 200 day moving average, you would buy or hold your position. On days where the 200 day average is more than the 50 day moving average, you would sell your shares. This strategy is called a trend following strategy. The positive or negative nature between the two temporal based averages represents the stock’s momentum.


The TTR package provides SMA() for calculating simple moving average. In this code snippet, you are examining the first 6 values for Twitter’s 200 and 50 day moving averages. SMA() works by passing in the time series data for a stock and a specific column like Close . This is a single vector of closing prices for the TWTR stock. The second parameter is an integer representing the number of observations for the moving average. Without using head() the SMA() function will return all values.


Now that you have examined the moving average function in detail, you need to apply to each of the 70 stocks. stocks. ts is a list of 70 data frames containing individual stock data. The fourth column of each data frame contains the closing price that we want to use for the moving averages.


The custom function mov. avgs() accepts a single stock data frame to calculate the moving averages. The first line selects the closing prices because it indexes [,4] to create stock. close . Next, the function uses ifelse to check the number of rows in the data frame. Specifically if the nrow in the data frame is less than (2*260) , then the function will create a data frame of moving averages with “NA”.


I chose this number because there is about 250 trading days a year so this will check that the time series is about 2 years or more in length. Loyal3 sometimes can get access to IPOs and if the stock is newly public there will not be enough data for a 200 day moving average. However, if the nrow value is greater than 2*260 then the function will create a data frame with the original data along with 200 and 50 day moving averages as new columns. Using colnames , I declare the column names. The last part of the function uses complete. cases to check for values in the 200 day moving average column. Any rows that do not have a value are dropped in the final result.


Armed with this mov. avgs() function you can use pblapply() to add the moving average calculations to each of the 70 data frames.


Use the code below to visualize a stock’s moving averages using a dygraph. Once again, this code is using the “%>%” operator to forward objects. The dygraph() function accepts the stocks. ts$FOX data frame. Specifically, the data frame is indexed by column name with c('sma_200','sma_50') . This object is passed to dySeries() in the next 2 lines. You can refer to a column by name so dySeries() each plot a line for the “sma_50” and “sma_200” values in lines 2 and 3. This object is forwarded again to the dyRangeSelector() to adjust the selector’s height. Lastly, I added some shading to define periods when you would have wanted to buy or hold the equity and a period when you should have sold your shares or stayed away depending on your position.


Here is the final result in an interactive time series.


The FOX moving averages with shaded regions for buying/holding versus selling.


استنتاج.


As a budding algorithmic trader, you do not need to plot all 70 shares. Instead, you would want to run the code every day and add a programmatic way to identify stocks that fit the rule based method, “buy if the 50 day moving average is above the 200 day moving average”. As you review the preceding chart, the green section is a time in which you would buy the FOX equity. The red section represents the time to sell your shares and not reenter.


Since the graph is interactive, you can use the slider to resize the visual. Based on this simple algo trading approach, now may be a good time to buy FOX! December 30, 2018 was a trading day where the 50 day moving average moved $0.01 higher than the 200 day moving average!


The zoomed section of the FOX equity.


Of course, remember all investments can lose value. To learn more about finance and algo trading,  check out DataCamp’s courses here.


و التاجر R.


Using R and related tools in Quantitative Finance.


Visualizing Time Series Data in R.


I’m very pleased to announce my DataCamp course on Visualizing Time Series Data in R. This course is also part of the Time Series with R skills track. Feel free to have a look, the first chapter is free!


وصف المساقات.


As the saying goes, “A chart is worth a thousand words”. This is why visualization is the most used and powerful way to get a better understanding of your data. After this course you will have a very good overview of R time series visualization capabilities and you will be able to better decide which model to choose for subsequent analysis. You will be able to also convey the message you want to deliver in an efficient and beautiful way.


بالطبع مخطط.


Chapter 1: R Time Series Visualization Tools.


This chapter will introduce you to basic R time series visualization tools.


Chapter 2: Univariate Time Series.


Univariate plots are designed to learn as much as possible about the distribution, central tendency and spread of the data at hand. In this chapter you will be presented with some visual tools used to diagnose univariate times series.


Chapter 3: Multivariate Time Series.


What to do if you have to deal with multivariate time series? In this chapter, you will learn how to identify patterns in the distribution, central tendency and spread over pairs or groups of data.


Chapter 4: Case study: Visually selecting a stock that improves your existing portfolio.


Let’s put everything you learned so far in practice! Imagine you already own a portfolio of stocks and you have some spare cash to invest, how can you wisely select a new stock to invest your additional cash? Analyzing the statistical properties of individual stocks vs. an existing portfolio is a good way of approaching the problem.


Linking R to IQFeed with the QuantTools package.


IQFeed provides streaming data services and trading solutions that cover the Agricultural, Energy and Financial marketplace. It is a well known and recognized data feed provider geared toward retail users and small institutions. The subscription price starts at around $80/month.


Stanislav Kovalevsky has developed a package called QuantTools. بل هو حزمة في كل واحدة تهدف إلى تعزيز النمذجة التداول الكمي. It allows to download and organize historical market data from multiple sources like Yahoo, Google, Finam, MOEX and IQFeed. The feature that interests me the most is the ability to link IQFeed to R. I’ve been using IQFeed for a few years and I’m happy with it (I’m not affiliated to the company in any way). More information can be found here. I’ve been looking for an integration within R for a while and here it is. As a result, after I ran a few tests, I moved my code that was still in Python into R. Just for completeness, here’s a link that explains how to download historical data from IQFeed using Python.


QuantTools offers four main functionalities: Get market data, Store/Retrieve market data, Plot time series data and Back testing.


First make sure that IQfeed is open. You can either download daily or intraday data. The below code downloads daily prices (Open, High, Low, Close) for SPY from 1st Jan 2017 to 1st June 2017.


The below code downloads intraday data from 1st May 2017 to 3rd May 2017.


Note the period parameter. It can take any of the following values: tick, 1min, 5min, 10min, 15min, 30min, hour, day, week, month, depending on the frequency you need.


QuantTools makes the process of managing and storing tick market data easy. You just setup storage parameters and you are ready to go. The parameters are where, since what date and which symbols you would like to be stored. Any time you can add more symbols and if they are not present in a storage, QuantTools tries to get the data from specified start date. The code below will save the data in the following directory: “C:/Users/Arnaud/Documents/Market Data/iqfeed”. There is one sub folder by instrument and the data is aved in. rds files.


You can also store data between specific dates. Replace the last line of code above with one of the below.


Now should you want to get back some of the data you stored, just run something like:


Note that only ticks are supported in local storage so period must be ‘tick’


QuantTools provides plot_ts function to plot time series data without weekend, holidays and overnight gaps. In the example below, I first retrieve the data stored above, then select the first 100 price observations and finally draw the chart.


Two things to notice: First spy is a data. table object hence the syntax above. To get a quick overview of data. table capabilities have a look at this excellent cheat sheet from DataCamp. Second the local parameter is TRUE as the data is retrieved from internal storage.


كوانتولس يسمح لكتابة استراتيجية التداول الخاصة بك باستخدام C ++ أبي. I’m not going to elaborate on this as this is basically C++ code. You can refer to the Examples section on QuantTools website.


Overall I find the package extremely useful and well documented. The only missing bit is the live feed between R and IQFeed which will make the package a real end to end solution.


As usual any comments welcome.


BERT: a newcomer in the R Excel connection.


A few months ago a reader point me out this new way of connecting R and Excel. I don’t know for how long this has been around, but I never came across it and I’ve never seen any blog post or article about it. So I decided to write a post as the tool is really worth it and before anyone asks, I’m not related to the company in any way.


BERT stands for Basic Excel R Toolkit. It’s free (licensed under the GPL v2) and it has been developed by Structured Data LLC. At the time of writing the current version of BERT is 1.07. More information can be found here. From a more technical perspective, BERT is designed to support running R functions from Excel spreadsheet cells. In Excel terms, it’s for writing User-Defined Functions (UDFs) in R.


In this post I’m not going to show you how R and Excel interact via BERT. There are very good tutorials here, here and here. Instead I want to show you how I used BERT to build a “control tower” for my trading.


My trading signals are generated using a long list of R files but I need the flexibility of Excel to display results quickly and efficiently. As shown above BERT can do this for me but I also want to tailor the application to my needs. By combining the power of XML, VBA, R and BERT I can create a good looking yet powerful application in the form of an Excel file with minimum VBA code. Ultimately I have a single Excel file gathering all the necessary tasks to manage my portfolio: database update, signal generation, orders submission etc… My approach could be broken down in the 3 steps below:


Use XML to build user defined menus and buttons in an Excel file. The above menus and buttons are essentially calls to VBA functions. Those VBA functions are wrapup around R functions defined using BERT.


With this approach I can keep a clear distinction between the core of my code kept in R, SQL and Python and everything used to display and format results kept in Excel, VBA & XML. In the next sections I present the prerequisite to developed such an approach and a step by step guide that explains how BERT could be used for simply passing data from R to Excel with minimal VBA code.


1 & # 8211؛ Download and install BERT from this link . Once the installation has completed you should have a new Add-Ins menu in Excel with the buttons as shown below. This is how BERT materialized in Excel.


2 & # 8211؛ Download and install Custom UI editor : The Custom UI Editor allows to create user defined menus and buttons in Excel ribbon. A step by step procedure is available here.


1 & # 8211؛ R Code: The below R function is a very simple piece of code for illustration purposes only. It calculates and return the residuals from a linear regression. This is what we want to retrieve in Excel. Save this in a file called myRCode. R (any other name is fine) in a directory of your choice.


2 & # 8211؛ functions. R in BERT : From Excel select Add-Ins -> Home Directory and open the file called functions. R . In this file paste the following code. Make sure you insert the correct path.


This is just sourcing into BERT the R file you created above. Then save and close the file functions. R. Should you want to make any change to the R file created in step 1 you will have to reload it using the BERT button “Reload Startup File” from the Add-Ins menu in Excel.


3 & # 8211؛ In Excel: Create and save a file called myFile. xslm (any other name is fine). This is a macro-enabled file that you save in the directory of your choice. Once the file is saved close it.


4 & # 8211؛ Open the file created above in Custom UI editor : Once the file is open, paste the below code.


You should have something like this in the XML editor:


Essentially this piece of XML code creates an additional menu (RTrader), a new group (My Group) and a user defined button (New Button) in the Excel ribbon. Once you’re done, open myFile. xslm in Excel and close the Custom UI Editor. You should see something like this.


5 & ​​# 8211؛ Open VBA editor : In myFile. xlsm insert a new module. Paste the code below in the newly created module.


This erases previous results in the worksheet prior to coping new ones.


6 & # 8211؛ Click New Button : Now go back to the spreadsheet and in the RTrader menu click the “New Button” زر. You should see something like the below appearing.


The guide above is a very basic version of what can be achieved using BERT but it shows you how to combine the power of several specific tools to build your own custom application. From my perspective the interest of such an approach is the ability to glue together R and Excel obviously but also to include via XML (and batch) pieces of code from Python, SQL and more. This is exactly what I needed. Finally I would be curious to know if anyone has any experience with BERT?


Trading strategy: Making the most of the out of sample data.


When testing trading strategies a common approach is to divide the initial data set into in sample data: the part of the data designed to calibrate the model and out of sample data: the part of the data used to validate the calibration and ensure that the performance created in sample will be reflected in the real world. As a rule of thumb around 70% of the initial data can be used for calibration (i. e. in sample) and 30% for validation (i. e. out of sample). Then a comparison of the in and out of sample data help to decide whether the model is robust enough. This post aims at going a step further and provides a statistical method to decide whether the out of sample data is in line with what was created in sample.


In the chart below the blue area represents the out of sample performance for one of my strategies.


A simple visual inspection reveals a good fit between the in and out of sample performance but what degree of confidence do I have in this? At this stage not much and this is the issue. What is truly needed is a measure of similarity between the in and out of sample data sets. In statistical terms this could be translated as the likelihood that the in and out of sample performance figures coming from the same distribution. There is a non-parametric statistical test that does exactly this: the Kruskall-Wallis Test . A good definition of this test could be found on R-Tutor “A collection of data samples are independent if they come from unrelated populations and the samples do not affect each other. Using the Kruskal-Wallis Test , we can decide whether the population distributions are identical without assuming them to follow the normal distribution.” The added benefit of this test is not assuming a normal distribution.


It exists other tests of the same nature that could fit into that framework. The Mann-Whitney-Wilcoxon test or the Kolmogorov-Smirnov tests would perfectly suits the framework describes here however this is beyond the scope of this article to discuss the pros and cons of each of these tests. A good description along with R examples can be found here.


Here’s the code used to generate the chart above and the analysis:


In the example above the in sample period is longer than the out of sample period therefore I randomly created 1000 subsets of the in sample data each of them having the same length as the out of sample data. Then I tested each in sample subset against the out of sample data and I recorded the p-values. This process creates not a single p-value for the Kruskall-Wallis test but a distribution making the analysis more robust. In this example the mean of the p-values is well above zero (0.478) indicating that the null hypothesis should be accepted: there are strong evidences that the in and out of sample data is coming from the same distribution.


As usual what is presented in this post is a toy example that only scratches the surface of the problem and should be tailored to individual needs. However I think it proposes an interesting and rational statistical framework to evaluate out of sample results.


This post is inspired by the following two papers:


Vigier Alexandre, Chmil Swann (2007), “Effects of Various Optimization Functions on the Out of Sample Performance of Genetically Evolved Trading Strategies”, Forecasting Financial Markets Conference.


Vigier Alexandre, Chmil Swann (2018), « An optimization process to improve in/out of sample consistency, a Stock Market case», JP Morgan Cazenove Equity Quantitative Conference, London October 2018.


Introducing fidlr: FInancial Data LoadeR.


fidlr is an RStudio addin designed to simplify the financial data downloading process from various providers. This initial version is a wrapper around the getSymbols function in the quantmod package and only Yahoo, Google, FRED and Oanda are supported. I will probably add functionalities over time. As usual with those things just a kind reminder: “THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND…”


How to install and use fidlr?


You can get the addin/package from its Github repository here (I will register it on CRAN later on) Install the addin. There is an excellent tutorial to install RStudio Addins here. Once the addin is installed it should appear in the Addin menu. Just chose fidlr in the menu and a window as pictured below should appear. Choose a data provider from the the Source dropdown menu. Select a date range from the Date menu Enter the symbol you wish to download in the instrument text box. To download several symbols just enter the symbols separated by commas. Use the Radio buttons to choose whether you want to download the instrument in a csv file or in the global environment. The csv file will be saved in the working directory and there will be one csv file per instrument. Press Run to get the data or Close to close down the addin.


Error messages and warnings are handled by the underlying packages (quantmod and Shiny) and can be read from the console.


This is a very first version of the project so do not expect perfection but hopefully it will get better over time. Please report any comment, suggestion, bug etc… to: thertrader@gmail.


Maintaining a database of price files in R.


Doing quantitative research implies a lot of data crunching and one needs clean and reliable data to achieve this. What is really needed is clean data that is easily accessible (even without an internet connection). The most efficient way to do this for me has been to maintain a set of csv files. Obviously this process can be handled in many ways but I found very efficient and simple overtime to maintain a directory where I store and update csv files. I have one csv file per instrument and each file is named after the instrument it contains. The reason I do so is twofold: First, I don’t want to download (price) data from Yahoo, Google etc… every time I want to test a new idea but more importantly once I identified and fixed a problem, I don’t want to have to do it again the next time I need the same instrument. Simple yet very efficient so far. The process is summarized in the chart below.


In everything that follows, I assume that data is coming from Yahoo. The code will have to be amended for data from Google, Quandl etc… In addition I present the process of updating daily price data. The setup will be different for higher frequency data and other type of dataset (i. e. different from prices).


1 & # 8211؛ Initial data downloading (listOfInstruments. R & historicalData. R)


The file listOfInstruments. R is a file containing only the list of all instruments.


If an instrument isn’t part of my list (i. e. no csv file in my data folder) or if you do it for the very first time you have to download the initial historical data set. The example below downloads a set of ETFs daily prices from Yahoo Finance back to January 2000 and store the data in a csv file.


2 & # 8211؛ Update existing data (updateData. R)


The below code starts from existing files in the dedicated folder and updates all of them one after the other. I usually run this process everyday except when I’m on holiday. To add a new instrument, simply run step 1 above for this instrument alone.


3 & # 8211؛ Create a batch file (updateDailyPrices. bat)


Another important part of the job is creating a batch file that automates the updating process above (I’m a Windows user). This avoids opening R/RStudio and run the code from there. The code below is placed on a. bat file (the path has to be amended with the reader’s setup). Note that I added an output file (updateLog. txt) to track the execution.


The process above is extremely simple because it only describes how to update daily price data. I’ve been using this for a while and it has been working very smoothly for me so far. For more advanced data and/or higher frequencies, things can get much trickier.


As usual any comments welcome.


The Rise of the Robots (Advisors…)


The Asset Management industry is on the verge of a major change. Over the last couple of years Robots Advisors (RA) have emerged as new players. The term itself is hard to define as it encompasses a large variety of services. Some are designed to help traditional advisers to better allocate their clients money and some are real “black box”. The user enter a few criteria (age , income, children etc…) and the robot proposes a tailor-made allocation. Between those two extremes a full range of offers is available. I found the Wikipedia definition pretty good. “They are a class of financial adviser that provides portfolio management online with minimal human intervention”. More precisely they use algorithm-based portfolio management to offer the full spectrum of services a traditional adviser would offer: dividend reinvesting, compliance reports, portfolio rebalancing, tax loss harvesting etc… (well this is what the quantitative investment community is doing for decades!). The industry is still in its infancy with most players still managing a small amount of money but I only realised how profound the change was when I was in NYC a few days ago. When RA get their names on TV adds or on the roof of NYC cab you know something big is happening…


it is getting more and more attention from the media and above all it makes a lot of sense from an investor perspective. There are actually two main advantages in using RA:


Significantly lower fees over traditional advisers Investment is made more transparent and simpler which is more appealing to people with limited financial knowledge.


In this post R is just an excuse to present nicely what is a major trend in the asset management industry. The chart below shows the market shares of most popular RA as of the end of 2018. The code used to generate the chart below can be found at the end of this post and the data is here.


Those figures are a bit dated given how fast this industry evolves but are still very informative. Not surprisingly the market is dominated by US providers like Wealthfront and Betterment but RA do emerge all over the world: Asia (8Now!), Switzerland (InvestGlass), France (Marie Quantier)….. It is starting to significantly affect the way traditional asset managers are doing business. A prominent example is the partnership between Fidelity and Betterment. Since December 2018 Betterment past the $2 billion AUM mark.


Despite all the above, I think the real change is ahead of us. Because they use less intermediaries and low commission products (like ETFs) they charge much lower fees than traditional advisers. RA will certainly gain significant market shares but they will also lowers fees charged by the industry as a whole. Ultimately it will affect the way traditional investment firms do business. Active portfolio management which is having a tough time for some years now will suffer even more. The high fees it charges will be even harder to justify unless it reinvents itself. Another potential impact is the rise of ETFs and low commission financial products in general. Obviously this has started a while ago but I do think the effect will be even more pronounced in the coming years. New generations of ETFs track more complex indices and custom made strategies. This trend will get stronger inevitably.


As usual any comments welcome.


R financial time series tips everyone should know about.


There are many R time series tutorials floating around on the web this post is not designed to be one of them. Instead I want to introduce a list of the most useful tricks I came across when dealing with financial time series in R. Some of the functions presented here are incredibly powerful but unfortunately buried in the documentation hence my desire to create a dedicated post. I only address daily or lower frequency times series. Dealing with higher frequency data requires specific tools: data. table or highfrequency packages are some of them.


xts : The xts package is the must have when it comes to times series in R. The example below loads the package and creates a daily time series of 400 days normaly distributed returns.


merge. xts (package xts): This is incredibly powerful when it comes to binding two or more times series together whether they have the same length or not. The join argument does the magic! it determines how the binding is done.


apply. yearly/apply. monthly (package xts): Apply a specified function to each distinct period in a given time series object. The example below calculates monthly and yearly returns of the second series in the tsInter object. Note that I use the sum of returns (no compounding)


endpoints (package xts): Extract index values of a given xts object corresponding to the last observations given a period specified by on. The example gives the last day of the month returns for each series in the tsInter object using endpoint to select the date.


na. locf (package zoo): Generic function for replacing each NA with the most recent non-NA prior to it. Extremely useful when dealing with a time series with a few “holes” and when this time series is subsequently used as input for an R functions that does not accept arguments with NAs. In the example I create a time series of random prices then artificially includes a few NAs in it and replace them with the most recent value.


charts. PerformanceSummary (package PerformanceAnalytics): For a set of returns, create a wealth index chart, bars for per-period performance, and underwater chart for drawdown. This is incredibly useful as it displays on a single window all the relevant information for a quick visual inspection of a trading strategy. The example below turns the prices series into an xts object then displays a window with the 3 charts described above.


The list above is by no means exhaustive but once you master the functions describe in this post it makes the manipulation of financial time series a lot easier, the code shorter and the readability of the code better.


As usual any comments welcome.


Factor Evaluation in Quantitative Portfolio Management.


When it comes to managing a portfolio of stocks versus a benchmark the problem is very different from defining an absolute return strategy. In the former one has to hold more stocks than in the later where no stocks at all can be held if there is not good enough opportunity. The reason for that is the tracking error . This is defined as the standard deviation of the portfolio return minus the benchmark return. The less stocks is held vs. a benchmark the higher the tracking error (e. g higher risk).


The analysis that follows is largely inspired by the book “Active Portfolio Management” by Grinold & Kahn. This is the bible for anyone interested in running a portfolio against a benchmark. I strongly encourage anyone with an interest in the topic to read the book from the beginning to the end. It’s very well written and lays the foundations of systematic active portfolio management (I have no affiliation to the editor or the authors).


Here we’re trying to rank as accurately as possible the stocks in the investment universe on a forward return basis. Many people came up with many tools and countless variant of those tools have been developed to achieve this. In this post I focus on two simple and widely used metrics: Information Coefficient (IC) and Quantiles Return (QR).


The IC gives an overview of the factor forecasting ability. More precisely, this is a measure of how well the factor ranks the stocks on a forward return basis. The IC is defined as the rank correlation ( ρ ) between the metric (e. g. factor) and the forward return. In statistical terms the rank correlation is a nonparametric measure of dependance between two variables. For a sample of size n , the n raw scores are converted to ranks , and ρ is computed from:


The horizon for the forward return has to be defined by the analyst and it’s a function of the strategy’s turnover and the alpha decay (this has been the subject of extensive research). Obviously ICs must be as high as possible in absolute terms.


For the keen reader, in the book by Grinold & Kahn a formula linking Information Ratio (IR) and IC is given: with breadth being the number of independent bets (trades). This formula is known as the fundamental law of active management . The problem is that often, defining breadth accurately is not as easy as it sounds.


In order to have a more accurate estimate of the factor predictive power it’s necessary to go a step further and group stocks by quantile of factor values then analyse the average forward return (or any other central tendency metric) of each of those quantiles. The usefulness of this tool is straightforward. A factor can have a good IC but its predictive power might be limited to a small number of stocks. This is not good as a portfolio manager will have to pick stocks within the entire universe in order to meet its tracking error constraint. Good quantiles return are characterised by a monotonous relationship between the individual quantiles and forward returns.


All the stocks in the S&P500 index (at the time of writing). Obviously there is a survival ship bias: the list of stocks in the index has changed significantly between the start and the end of the sample period, however it’s good enough for illustration purposes only.


The code below downloads individual stock prices in the S&P500 between Jan 2005 and today (it takes a while) and turns the raw prices into return over the last 12 months and the last month. The former is our factor, the latter will be used as the forward return measure.


Below is the code to compute Information Coefficient and Quantiles Return. Note that I used quintiles in this example but any other grouping method (terciles, deciles etc…) can be used. it really depends on the sample size, what you want to capture and wether you want to have a broad overview or focus on distribution tails. For estimating returns within each quintile, median has been used as the central tendency estimator. This measure is much less sensitive to outliers than arithmetic mean.


And finally the code to produce the Quantiles Return chart.


3 & # 8211؛ How to exploit the information above?


In the chart above Q1 is lowest past 12 months return and Q5 highest. There is an almost monotonic increase in the quantiles return between Q1 and Q5 which clearly indicates that stocks falling into Q5 outperform those falling into Q1 by about 1% per month. This is very significant and powerful for such a simple factor (not really a surprise though…). Therefore there are greater chances to beat the index by overweighting the stocks falling into Q5 and underweighting those falling into Q1 relative to the benchmark.


An IC of 0.0206 might not mean a great deal in itself but it’s significantly different from 0 and indicates a good predictive power of the past 12 months return overall. Formal significance tests can be evaluated but this is beyond the scope of this article.


The above framework is excellent for evaluating investments factor’s quality however there are a number of practical limitations that have to be addressed for real life implementation:


Rebalancing : In the description above, it’s assumed that at the end of each month the portfolio is fully rebalanced. This means all stocks falling in Q1 are underweight and all stocks falling in Q5 are overweight relative to the benchmark. This is not always possible for practical reasons: some stocks might be excluded from the investment universe, there are constraints on industry or sector weight, there are constraints on turnover etc… Transaction Costs : This has not be taken into account in the analysis above and this is a serious brake to real life implementation. Turnover considerations are usually implemented in real life in a form of penalty on factor quality. Transfer coefficient : This is an extension of the fundamental law of active management and it relaxes the assumption of Grinold’s model that managers face no constraints which preclude them from translating their investments insights directly into portfolio bets.


And finally, I’m amazed by what can be achieved in less than 80 lines of code with R…


As usual any comments welcome.


Risk as a “Survival Variable”


I come across a lot of strategies on the blogosphere some are interesting some are a complete waste of time but most share a common feature: people developing those strategies do their homework in term of analyzing the return but much less attention is paid to the risk side its random nature. I’ve seen comment like “a 25% drawdown in 2018 but excellent return overall”. Well my bet is that no one on earth will let you experience a 25% loss with their money (unless special agreements are in place). In the hedge fund world people have very low tolerance for drawdown. Generally, as a new trader in a hedge fund, assuming that you come with no reputation, you have very little time to prove yourself. You should make money from day 1 and keep on doing so for a few months before you gain a bit of credibility.


First let’s say you have a bad start and you lose money at the beginning. With a 10% drawdown you’re most certainly out but even with a 5% drawdown the chances of seeing your allocation reduced are very high. This has significant implications on your strategies. Let’s assume that if you lose 5% your allocation is divided by 2 and you come back to your initial allocation only when you passed the high water mark again (e. g. the drawdown comes back to 0). In the chart below I simulated the experiment with one of my strategies.


You start trading in 1st June 2003 and all goes well until 23rd Jul. 2003 where your drawdown curve hits the -5% threshold (**1**). Your allocation is cut by 50% and you don’t cross back the high water mark level until 05th Dec. 2003 (**3**). If you have kept the allocation unchanged, the high water mark level would have been crossed on 28th Oct. 2003 (**2**) and by the end of the year you would have made more money.


But let’s push the reasoning a bit further. Still on the chart above, assume you get really unlucky and you start trading toward mid-June 2003. You hit the 10% drawdown limit by the beginning of August and you’re most likely out of the game. You would have started in early August your allocation would not have been cut at all and you end up doing a good year in only 4 full months of trading. In those two examples nothing has changed but your starting date….


The trading success of any individual has some form of path dependency and there is not much you can do about it. However you can control the size of a strategy’s drawdown and this should be addressed with great care. A portfolio should be diversified in every possible dimension: asset classes, investment strategies, trading frequencies etc…. From that perspective risk is your “survival variable”. If managed properly you have a chance to stay in the game long enough to realise the potential of your strategy. Otherwise you won’t be there next month to see what happens.

No comments:

Post a Comment